package com.example.myspringbootdemojava1.controller;

import com.example.myspringbootdemojava1.domain.Book;
import com.example.myspringbootdemojava1.domain.Code;
import com.example.myspringbootdemojava1.domain.Result;
import com.example.myspringbootdemojava1.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 黑马程序员
 */
@RestController
//@RequestMapping("books") //在springmvc中的路径映射里面第一个“/”可以省略
@RequestMapping("/books")
public class BookController {

    //注入业务对象
    @Autowired
    private BookService bookService;

    //新增, 通过请求体传递新增的数据
    //@RequestBody 获取请求体数据转换为java对象
    @PostMapping
    public Result save(@RequestBody Book book){
        bookService.save(book);
        return Result.success(Code.SAVE_OK,true);
    }

    //删除,通过路径变量传递id数据
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        bookService.delete(id);
        return Result.success(Code.DELETE_OK,true);
    }

    //修改, 通过请求体传递新增的数据
    @PutMapping
    public Result update(@RequestBody Book book){
        bookService.update(book);
        return Result.success(Code.UPDATE_OK,true);
    }

    //查询所有书
    @GetMapping
    public Result getAll(){
        List<Book> bookList = bookService.getAll();
        return Result.success(Code.GET_OK,bookList);
    }

    //查询一本书，通过路径变量传递id数据
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return  Result.success(Code.GET_OK,bookService.getById(id));
    }
}
